package com.ecloud.gardensterminal.server.mqtt;

import com.alibaba.fastjson.JSON;
import com.ecloud.gardensterminal.constant.MqttTopic;
import com.ecloud.gardensterminal.controller.dto.GardensMqttCallback;
import com.ecloud.gardensterminal.mqtt.constant.MqttMessageArrivedCall;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Squbi
 */
@Component
public class MqttCallBackService implements MqttMessageArrivedCall {
    private static final Logger LOGGER = LoggerFactory.getLogger(MqttCallBackService.class);
    @Autowired
    private MqttServiceImpl service;

    @Override
    public void exec(String topic, MqttMessage message) {
        if (topic.equals(MqttTopic.SERVER_TOPIC)) {
            server(message);
        } else if (topic.equals(MqttTopic.LOCAL_TOPIC)) {
            local(message);
        } else if (topic.equals(MqttTopic.TERMINAL_TOPIC)) {
            localTerminal(message);
        } else {
            other(topic, message);
        }
    }

    private void server(MqttMessage message) {
        LOGGER.info("message from server : {}", message);
    }

    private void local(MqttMessage message) {
        LOGGER.info("message from local : {}", message);
    }

    private void localTerminal(MqttMessage message) {
        LOGGER.info("message from local terminal: {}", message);
        String json = new String(message.getPayload());
        GardensMqttCallback call = JSON.parseObject(json, GardensMqttCallback.class);
        service.callback(call);
        LOGGER.info("local terminal exec success");
    }

    private void other(String topic, MqttMessage message) {
        LOGGER.info("message from `{}` topic : {}", topic, message);
    }
}
